<?php
// +----------------------------------------------------------------------
// | HkCms
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2019 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

namespace common\model;

use think\Db;
use think\Validate;

class Config extends Model
{

    protected static function init()
    {
        self::event('before_write', function ($user) {

            cache('Config', NULL);
        });
    }

    /**
     * 增加扩展配置项
     * @param type $data
     * @return boolean
     */
    public function extendAdd($data) 
    {

        if (empty($data)) {

            $this->error = '数据不能为空！';

            return false;
        }
        if (empty($data['setting']['title'])) {

            $this->error = '名称不能为空！';

            return false;
        }

        $data['fieldname'] = strtolower($data['fieldname']);

        $rule = [

            ['fieldname',['require','/^[a-z_0-9]+$/i','unique:ConfigField'],'键名不能为空!|键名只支持英文、数字、下划线！|该键名已经存在！'],

            ['type','require','类型不能为空！']
        ];
        
        $validate = new Validate($rule);

        $result   = $validate->check($data);

        if(!$result){

            $this->error = $validate->getError();

            return false;
        }

        $db = Db::name('ConfigField');
        
        $data['createtime'] = time();

        //检查config表是否已经存在
        if ($this->where('varname',$data['fieldname'])->count()) {

            $this->error = '该键名已经存在！';

            return false;
        }

        $setting = $data['setting'];

        if ($data['type'] == 'radio' || $data['type'] == 'select') {

            $option = array();

            $optionList = explode("\n", $setting['option']);

            if (is_array($optionList)) {

                foreach ($optionList as $rs) {

                    $rs = explode('|', $rs);

                    if (!empty($rs)) {

                        $option[] = array(

                            'title' => $rs[0],

                            'value' => $rs[1],
                        );
                    }
                }

                $setting['option'] = $option;
            }
        }

        $data['setting'] = serialize($setting);

        // 去除post
        unset($data['']);

        $id = Db::name('ConfigField')->insert($data);

        if ($id) {

            // 增加配置项
            $this->data([
                'varname' => $data['fieldname'],
                'info' => $setting['title'],
                'groupid' => 2,
                'value' => '',
            ])->allowField(true)->save();

            return $id;

        } else {

            $this->error = '添加失败！';

            return false;
        }
      
    }

    /**
     * 删除扩展配置项
     * @param type $fid 配置项ID
     * @return boolean
     */
    public function extendDel($fid) 
    {
        if (empty($fid)) {

            $this->error = '请指定需要删除的扩展配置项！';

            return false;
        }

        //扩展字段详情
        $info = Db::name('ConfigField')->where(['fid' => $fid])->find();

        if (empty($info)) {

            $this->error = '该扩展配置项不存在！';

            return false;
        }

        //删除
        if ($this->where(array('varname' => $info['fieldname'], 'groupid' => 2))->delete() !== false) {

            Db::name('ConfigField')->where(array('fid' => $fid))->delete();

            return true;

        } else {

            $this->error = '删除失败！';
            
            return false;
        }
    }

    /**
     * 更新扩展配置项
     * @param type $data 数据
     * @return boolean
     */
    public function saveExtendConfig($data) 
    {
        if (empty($data) || !is_array($data)) {

            $this->error = '配置数据不能为空！';

            return false;
        }

        // //令牌验证
        // if (!$this->autoCheckToken($data)) {
        //     $this->error = L('_TOKEN_ERROR_');
        //     return false;
        // }
        // //去除token
        // unset($data[C("TOKEN_NAME")]);

        foreach ($data as $key => $value) {

            if (empty($key)) {

                continue;
            }
            
            if ( ($this->allowField(true)->save(['value' => trim($value)],["varname" => $key, 'groupid' => 2])) === false) {

                $this->error = "更新到{$key}项时，更新失败！";

                return false;
            }
        }
        return true;
    }

    /**
     * 更新网站配置项
     * @param type $data 数据
     * @return boolean
     */
    public function saveConfig($data) {
        if (empty($data) || !is_array($data)) {
            $this->error = '配置数据不能为空！';
            return false;
        }
        // //令牌验证
        // if (!$this->autoCheckToken($data)) {
        //     $this->error = L('_TOKEN_ERROR_');
        //     return false;
        // }
        // //去除token
        // unset($data[C("TOKEN_NAME")]);
        foreach ($data as $key => $value) {
            if (empty($key)) {
                continue;
            }
            $saveData = array();
            $saveData["value"] = trim($value);
            if ($this->where("varname",$key)->update($saveData) === false) {
                $this->error = "更新到{$key}项时，更新失败！";
                return false;
            }
        }
        return true;
    }

    /**
     * 保存高级配置
     * @param type $data 配置信息
     * @return boolean
     */
    public function addition($data) 
    {
        if (empty($data)) {

            $this->error = '没有数据！';

            return false;
        }

        //配置文件地址
         $filename = CONF_PATH . 'addition.php';
        //检查文件是否可写
        if (is_writable($filename) == false) {

            $this->error = '请检查[' . CONF_PATH . 'config.php' . ']文件权限是否可写！';

            return false;
        }

        if (isset($data[config('TOKEN_NAME')])) {

            unset($data[config('TOKEN_NAME')]);
        }

        //**********************检测一些设置，会导致网站瘫痪的**********************
        //缓存类型检测
        if (!empty($data['DATA_CACHE_TYPE']) && $data['DATA_CACHE_TYPE'] == 'Memcache') {

            if (class_exists('Memcache') == false) {

                $this->error = '您的环境不支持Memcache，无法开启！';

                return false;
            }
        }

        if (!empty($data['DATA_CACHE_TYPE']) && $data['DATA_CACHE_TYPE'] == 'Redis') {

            if (class_exists('Redis') == false) {

                $this->error = '您的环境不支持Redis，无法开启！';

                return false;
            }
        }

        if (!empty($data['DATA_CACHE_TYPE']) && $data['DATA_CACHE_TYPE'] == 'Xcache') {

            if (function_exists('xcache_set') == false) {

                $this->error = '您的环境不支持Xcache，无法开启！';

                return false;
            }
        }
        //***********************END************************************

        file_exists($filename) or touch($filename);

        //$return = var_export($data, TRUE);
        $return = include $filename;
        if (!empty($data['cloud_username'])) {
            $return['cloud_username'] = $data['cloud_username'];
        }
        if (!empty($data['cloud_password'])) {
            $return['cloud_password'] = $data['cloud_password'];
        }
        if (!empty($data['cookie']['expire'])) {
            $return['cookie']['expire'] = $data['cookie']['expire'];
        }
        if (!empty($data['cookie']['domain'])) {
            $return['cookie']['domain'] = $data['cookie']['domain'];
        }
        if (!empty($data['cookie']['path'])) {
            $return['cookie']['path'] = $data['cookie']['path'];
        }

        if (!empty($data['session']['prefix'])) {
            $return['session']['prefix'] = $data['session']['prefix'];
        }
        if (!empty($data['session']['domain'])) {
            $return['session']['domain'] = $data['session']['domain'];
        }

        if (!empty($data['show_error_msg'])) {
            $return['show_error_msg'] = $data['show_error_msg'];
        }
        if (!empty($data['error_message'])) {
            $return['error_message'] = $data['error_message'];
        }
        if (!empty($data['pathinfo_depr'])) {
            $return['pathinfo_depr'] = $data['pathinfo_depr'];
        }
        if (!empty($data['url_html_suffix'])) {
            $return['url_html_suffix'] = $data['url_html_suffix'];
        }

        if (!empty($data['paginate']['list_rows'])) {
            $return['paginate']['list_rows'] = $data['paginate']['list_rows'];
        }
        if (!empty($data['paginate']['var_page'])) {
            $return['paginate']['var_page'] = $data['paginate']['var_page'];
        }
        if (!empty($data['default_module'])) {
            $return['default_module'] = $data['default_module'];
        }
        if (!empty($data['default_timezone'])) {
            $return['default_timezone'] = $data['default_timezone'];
        }
        if (!empty($data['default_ajax_return'])) {
            $return['default_ajax_return'] = $data['default_ajax_return'];
        }
        if (!empty($data['default_filter'])) {
            $return['default_filter'] = $data['default_filter'];
        }
        if (!empty($data['default_lang'])) {
            $return['default_lang'] = $data['default_lang'];
        }
        if (!empty($data['page_template'])) {
            $return['page_template'] = $data['page_template'];
        }
        $return = var_export($return,true);
        if ($return) {
            if (file_put_contents($filename, "<?php \r\n return " . $return . ";")) {
                return true;
            } else {
                $this->error = '配置更新失败！';
                return false;
            }
        } else {
            $this->error = '配置数据为空！';
            return false;
        }
    }

    /**
     * 缓存数据
     * @return array
     */
    public function config_cache()
    {
        $data = $this->column("varname,value");
        cache("Config", $data);
        return $data;
    }

}